<script lang="ts" setup>
import { ref, computed, onMounted, Ref } from "vue";
import { Edit, Delete } from "@element-plus/icons-vue";
import {
  createInstitution,
  getAllInstitutions,
  deleteInstitution,
  updateInstitution,
} from "@/axios/applicant/applicantReq";
import ApplicationInstitution from "@/types/response/applicantIns";
import { ElMessage } from "element-plus";
import useFileStore from "@/stores/fileStore";
import ApplicantToInstitution from "@/types/response/applicantToIns";
let fileStore = useFileStore();
//用户搜索时输入的名字
const name = ref("");

const applicationIns: Ref<ApplicationInstitution[]> = ref([]);

// 控制添加申请机构弹窗
const dialogVisible = ref(false);

const rulesFormRef = ref();

// 添加申请机构数据模型
const applicationInsModel:Ref<ApplicationInstitution> = ref(new ApplicationInstitution());

// 添加申请机构表单校验
const rules = {
  name: [{ required: true, message: "请输入申请机构名称", trigger: "blur" }],
  license: [{ required: true, message: "请上传营业执照", trigger: "blur" }],
  creditCode: [
    { required: true, message: "请输入统一社会信用代码", trigger: "blur" },
  ],
  unitType: [{ required: true, message: "请输入单位类型", trigger: "blur" }],
  legalMan: [{ required: true, message: "请输入法定代表人", trigger: "blur" }],
  legalManCreditType: [
    { required: true, message: "请上传法定代表人证件类型", trigger: "blur" },
  ],
  legalManSupport: [
    { required: true, message: "请输入法定代表人证明", trigger: "blur" },
  ],
  director: [{ required: true, message: "请输入负责人", trigger: "blur" }],
  directorPhone: [
    { required: true, message: "请输入负责人联系方式", trigger: "blur" },
  ],
  companyAddress: [
    { required: true, message: "请输入公司地址", trigger: "blur" },
  ],
};
//添加申请机构函数
const addApplicationIns = () => {
  title.value = "新增申请机构";
  applicationInsModel.value=new ApplicationInstitution();
  dialogVisible.value = true;
  editIndex.value = null;
  rulesFormRef.value?.resetFields();
};
const editIndex = ref<number | null>(null);

const editApplicationIns = (index: number, applicationIns: any) => {
  title.value = "编辑申请机构";
  dialogVisible.value = true;
  applicationInsModel.value = { ...applicationIns };
  editIndex.value = index;
  rulesFormRef.value?.clearValidate();
};

const validateForm = () => {
  rulesFormRef.value.validate((valid) => {
    if (valid) {
      submitForm();
    }
  });
};

// 提交表单的方法
const submitForm = async () => {
  if (editIndex.value !== null) {
    //更新申请机构信息
    const success = await updateInstitution(applicationInsModel.value);
    if (success) {
      applicationIns.value[editIndex.value] = { ...applicationInsModel.value };
      editIndex.value = null;
      ElMessage({
        type: "success",
        message: "申请机构更新成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "申请机构更新失败",
      });
    }
  } else {
    //添加申请机构信息
    const success = await createInstitution(applicationInsModel.value);
    if (success) {
      applicationIns.value.push({ ...applicationInsModel.value });
      ElMessage({
        type: "success",
        message: "申请机构创建成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "申请机构创建失败",
      });
    }
  }

  // 这里可以添加保存到 applicationIns 数组的逻辑
  console.log("提交的申请机构信息:", applicationInsModel.value);
  dialogVisible.value = false;
};

// 删除申请机构的方法
const deleteApplicationIns = async (index: number) => {
  const applicationInstitutionId =
    applicationIns.value[index].applicationInstitutionId;
  const success = await deleteInstitution(applicationInstitutionId);
  if (success) {
    if (editIndex.value === index) {
      editIndex.value = null;
    }
    applicationIns.value.splice(index, 1);
    ElMessage({
      type: "success",
      message: "申请机构删除成功",
    });
  } else {
    ElMessage({
      type: "error",
      message: "申请机构删除失败",
    });
  }
};

const title = ref("");
const value1 = ref("");

const filteredApplicationIns = computed(() => {
  return applicationIns.value.filter(
    (applicationIns) => !name.value || applicationIns.name.includes(name.value)
  );
});
//详细信息抽屉
const table = ref(false);
const selectedApplicationIns = ref(null);

const openDrawer = (respondent: any) => {
  selectedApplicationIns.value = respondent;
  table.value = true;
};

// 获取所有申请机构信息
const fetchAllInstitutions = async () => {
  const institutions = await getAllInstitutions();
  if (institutions) {
    applicationIns.value = institutions;
  } else {
    console.error("获取申请机构信息失败");
  }
};

// 组件挂载时获取所有申请机构信息
onMounted(() => {
  fetchAllInstitutions();
});
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>申请机构管理</span>
        <div class="extra">
          <el-button type="primary" @click="addApplicationIns"
            >新增申请机构</el-button
          >
        </div>
      </div>
    </template>
    <!-- 搜素表单 -->
    <el-form inline>
      <el-form-item label="机构名称：">
        <el-input
          v-model="name"
          style="width: 240px"
          clearable
          placeholder="请输入机构"
        />
      </el-form-item>
    </el-form>

    <el-table :data="filteredApplicationIns" style="width: 100%">
      <el-table-column type="index" label="序号" width="100"></el-table-column>
      <el-table-column label="机构名称" prop="name"></el-table-column>
      <el-table-column label="法定代表人" prop="legalMan"></el-table-column>
      <el-table-column label="负责人" prop="director"></el-table-column>
      <el-table-column label="公司地址" prop="companyAddress"></el-table-column>
      <el-table-column label="营业执照">
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.license"
            :preview-src-list="[scope.row.license]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            :disabled="scope.row.state === '启用'"
            @click="editApplicationIns(scope.$index, scope.row)"
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            :disabled="scope.row.state === '启用'"
            @click="deleteApplicationIns(scope.$index)"
          ></el-button>
          <el-button text type="primary" @click="openDrawer(scope.row)"
            >详细</el-button
          >
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="title" width="30%">
      <el-form
        :model="applicationInsModel"
        :rules="rules"
        label-width="150px"
        style="padding-right: 30px"
        ref="rulesFormRef"
      >
        <el-form-item label="申请机构名称" prop="name">
          <el-input
            v-model="applicationInsModel.name"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>

        <el-form-item label="营业执照" prop="license">
          <el-button
            v-if="!applicationInsModel.license"
            type="primary"
            @click="
              () => {
                fileStore.selectFileToUpload('all', (res) => {
                  applicationInsModel.license = res.remoteUrl;
                });
              }
            "
            >上传执照</el-button
          >
          <el-image
            v-if="applicationInsModel.license"
            :src="applicationInsModel.license"
            fit="fill"
            @click="
              () => {
                fileStore.selectFileToUpload('all', (res) => {
                  applicationInsModel.license = res.remoteUrl;
                });
              }
            "
          >
          </el-image>
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input
            v-model="applicationInsModel.creditCode"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <!--
        <el-form-item label="单位类型" prop="unitType">
          <el-input v-model="applicationInsModel.unitType" minlength="2" maxlength="10"></el-input>
        </el-form-item>
        -->
        <el-form-item label="法定代表人" prop="legalMan">
          <el-input
            v-model="applicationInsModel.legalMan"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <!--  <el-form-item label="法定代表人证件类型" prop="legalManCreditType">
          <el-input v-model="applicationInsModel.legalManCreditType" minlength="2" maxlength="10"></el-input>
        </el-form-item>-->
        <el-form-item label="法定代表人证明" prop="legalManSupport">
          <el-button
            v-if="!applicationInsModel.legalManSupport"
            type="primary"
            @click="
              () => {
                fileStore.selectFileToUpload('all', (res) => {
                  applicationInsModel.legalManSupport = res.remoteUrl;
                });
              }
            "
            >上传证明</el-button
          >
          <el-image
            v-if="applicationInsModel.legalManSupport"
            :src="applicationInsModel.legalManSupport"
            fit="fill"
            @click="
              () => {
                fileStore.selectFileToUpload('all', (res) => {
                  applicationInsModel.legalManSupport = res.remoteUrl;
                });
              }
            "
          ></el-image>
        </el-form-item>
        <el-form-item label="负责人" prop="director">
          <el-input
            v-model="applicationInsModel.director"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人联系方式" prop="directorPhone">
          <el-input
            v-model="applicationInsModel.directorPhone"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="公司地址" prop="companyAddress">
          <el-input
            v-model="applicationInsModel.companyAddress"
            minlength="2"
            maxlength="10"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="validateForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
  <el-drawer
    v-model="table"
    title="申请机构详细信息"
    direction="rtl"
    size="50%"
  >
    <el-descriptions :column="1" border :data="selectedApplicationIns">
      <el-descriptions-item label="申请机构名称">{{
        selectedApplicationIns?.name
      }}</el-descriptions-item>
      <el-descriptions-item label="营业执照">
        <el-image
          style="width: 100px; height: 100px"
          :src="selectedApplicationIns?.license"
          fit="cover"
        />
      </el-descriptions-item>
      <el-descriptions-item label="统一社会信用代码">{{
        selectedApplicationIns?.creditCode
      }}</el-descriptions-item>
      <!-- <el-descriptions-item label="单位类型">{{ selectedApplicationIns?.unitType }}</el-descriptions-item>-->
      <el-descriptions-item label="法定代表人">{{
        selectedApplicationIns?.legalMan
      }}</el-descriptions-item>
      <!-- <el-descriptions-item label="法定代表人证件类型">{{ selectedApplicationIns?.legalManCreditType }}</el-descriptions-item>-->
      <el-descriptions-item label="法定代表人证明">
        <el-image
          style="width: 100px; height: 100px"
          :src="selectedApplicationIns?.legalManSupport"
          fit="cover"
        />
      </el-descriptions-item>
      <el-descriptions-item label="负责人">{{
        selectedApplicationIns?.director
      }}</el-descriptions-item>
      <el-descriptions-item label="负责人联系方式">{{
        selectedApplicationIns?.directorPhone
      }}</el-descriptions-item>
      <el-descriptions-item label="公司地址">{{
        selectedApplicationIns?.companyAddress
      }}</el-descriptions-item>
    </el-descriptions>
  </el-drawer>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
